package com.ffcs.cn.action.desktopcontrol.smDialogProgressTotal;

import com.supermap.desktop.controls.ui.controls.progress.FormProgressCancelledListener;
import com.supermap.desktop.controls.ui.controls.progress.SmDialogProgressTotal;
import com.supermap.desktop.core.Application;
import com.supermap.desktop.core.Interface.IBaseItem;
import com.supermap.desktop.core.implement.CtrlAction;
import com.supermap.desktop.core.progress.Interface.UpdateProgressCallable;

import java.util.concurrent.CancellationException;
import java.util.concurrent.TimeUnit;

/**
 * 双进度条
  *
 */
public class CtrlActionSmDialogProgressTotal extends CtrlAction {
	public CtrlActionSmDialogProgressTotal(IBaseItem caller) {
		super(caller);
	}

	@Override
	protected void run() {
		SmDialogProgressTotal progressTotal = new SmDialogProgressTotal("多进度条");
		//添加取消任务监听器
		progressTotal.addFormProgressCancelledListener(new FormProgressCancelledListener() {
			@Override
			public void formProgressCancelled() {
				Application.getActiveApplication().getOutput().output("任务已被取消");
			}
		});
		progressTotal.doWork(new UpdateProgressCallable() {
			@Override
			public Boolean call() throws Exception {
				int totalStart = 0;
				int totalEnd = 2;
				int start = 1;
				int end = 100;
				int timeout = 250;
				try {
					//默认任务执行
					for (int i = totalStart; i < totalEnd; i++) {
						for (int j = start; j <= end; j++) {
							int percent = (int)(j*1.0 / (end-start +1) * 100);
							int totalPercent = (int) ((i * 1.0 / (totalEnd-totalStart)) * 100 + (percent *1.0 / (totalEnd-totalStart)));
							String currentMessage = "任务"+ (i+1) +"，已执行 "+j +" / "+end;
							String totalMessage = "共有任务："+totalEnd+"个，正在执行任务 "+(i+1);
							long duration = ((totalEnd-totalStart)*(end-start +1) - (j+i *(end-start +1))) *timeout;
							String remainTime = TimeUnit.MILLISECONDS.toSeconds(duration)+ " 秒";
							TimeUnit.MILLISECONDS.sleep(timeout);
							//更新任务进度
							progressTotal.updateProgress(percent,totalPercent,currentMessage,totalMessage,remainTime,
									i+1,totalEnd);
						}
					}
					return true;
				}catch (CancellationException e){
					return false;
				}
			}
		});
	}
}
